package net.dgg.zz.common.files.controller;

import net.dgg.framework.tac.mongo.utils.DggMongoUtils;
import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.util.SslUtils;
import net.dgg.iboss.base.util.StringUtils;
import net.dgg.zz.common.constant.SystemCommonConstant;
import net.dgg.zz.common.files.entity.Annex;
import net.dgg.zz.common.files.entity.AnnexEnum;
import net.dgg.zz.common.files.service.AnnexService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.fblock.log.NLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * 附件上传
 *
 * @Author:HDC
 * @Date: Created in 2018/8/15 18:20
 * @Copyright © dgg group.All Rights Reserved. 版权信息
 */
@Controller
@RequestMapping("annex/")
public class AnnexController extends DggBaseController {

    @Autowired
    private AnnexService annexService;

    @Value("${dgg.oss[0].bucket-uri}")
    private String ossHost;
    @Value("${dgg.fdfs.fdfs-uri}")
    private String fastdfsHost;

    @Autowired
    private SystemRecordService systemRecordService;

    /**
     * 附件上传页面
     *
     * @return
     */
    @NLog()
    @RequestMapping("annex")
    public String annexPage() {
        return "zzsc/annex/annex";
    }


    /**
     * 附件上传页面
     *
     * @return
     */
    @NLog()
    @RequestMapping("show_annex")
    public String showAnnexPage() {
        return "zzsc/annex/show_annex";
    }

    /**
     * 获取fileId
     *
     * @return
     */
    @NLog()
    @RequestMapping(value = "get_file_id", method = RequestMethod.POST)
    @ResponseBody
    public DggRestResponse getFileId(String fileId) {
        if (StringUtils.isEmpty(fileId))
            fileId = String.valueOf(DggKeyWorker.nextId());
        return this.getSuccessResponse(fileId);

    }

    /**
     * 文件上传
     *
     * @param fileId
     * @param type
     * @param file
     * @return
     */
    @NLog()
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    public DggRestResponse uploadFile(String fileId, String type, @RequestParam MultipartFile file) {
        if (null == file) {
            return super.getFailResponse("文件不能为空");
        }
        long fileSize = file.getSize();
        if (fileSize > (20 * 1024 * 1024)) {
            return super.getFailResponse("文件不能超过20MB");
        }
        try {
            if (StringUtils.isEmpty(fileId)) {
                return this.getSuccessResponse("文件自定义Id为空");
            }
            fileId = SystemCommonConstant.ANNEX_FILE_ID_PREFIX + "_" + fileId;// 附件id命名规则：系统_数据Id_模块
            if (StringUtils.isNotEmpty(type)) {
                fileId = fileId + "_" + type;
            }
            Annex item = annexService.saveMultipartFile(fileId, file);
            // 保存操作日志
            SystemRecord systemRecord = new SystemRecord();
            systemRecord.setSource("5");
            systemRecord.setOperateType("1");
            systemRecord.setWorkId(1L);
            systemRecord.setWorkTableName("annex");
            systemRecord.setRemarks("上传文件：" + item.getFileid() + ":" + item.getFilename());
            systemRecordService.save(systemRecord);
            return super.getSuccessResponse(item);
        } catch (Exception ex) {
            ex.printStackTrace();
            return super.getFailResponse("上传失败(" + ex.getMessage() + ")，请联系管理员");
        }
    }


    /**
     * 查询文件
     *
     * @param fileId 文件ID
     * @return
     */
    @NLog()
    @RequestMapping(value = "find_file", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public DggRestResponse findFile(@RequestParam(required = false) String fileId, @RequestParam(required = false) String type) {
        try {
            if (StringUtils.isBlank(fileId)) {
                return super.getFailResponse("自定义文件ID不能为空");
            }
            fileId = SystemCommonConstant.ANNEX_FILE_ID_PREFIX + "_" + fileId;// 附件id命名规则：系统_数据Id_模块
            if (StringUtils.isNotEmpty(type)) {
                fileId = fileId + "_" + type;
            }
            List<Annex> files = annexService.findFile(fileId);
            if (null != files) {
                for (Annex file : files) {
                    if(AnnexEnum.UPLOAD_OSS.getOperateName().equals(file.getStorage().name())){
                        file.setFilepath(ossHost + file.getFilepath());
                    }else{
                        file.setFilepath(fastdfsHost + file.getFilepath());
                    }
                }
            }
            return super.getSuccessResponse(files);
        } catch (Exception ex) {
            ex.printStackTrace();
            return super.getFailResponse("获取文件系统错误，请联系管理员");
        }
    }

    /**
     * 根据文件名前缀匹配文件
     *
     * @param fileId 前缀ID
     * @return
     */
    @NLog()
    @RequestMapping(value = "find_files", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public DggRestResponse findFiles(@RequestParam(required = false) String fileId) {
        try {
            if (StringUtils.isBlank(fileId)) {
                return super.getFailResponse("自定义文件ID不能为空");
            }
            List<Annex> files = annexService.findFiles(fileId);
            if (null != files) {
                for (Annex file : files) {
                    if(AnnexEnum.UPLOAD_OSS.getOperateName().equals(file.getStorage().name())){
                        file.setFilepath(ossHost + file.getFilepath());
                    }else{
                        file.setFilepath(fastdfsHost + file.getFilepath());
                    }
                }
            }
            return super.getSuccessResponse(files);
        } catch (Exception ex) {
            ex.printStackTrace();
            return super.getFailResponse("获取文件系统错误，请联系管理员");
        }
    }

    /**
     * 文件删除
     *
     * @param fileId   文件ID
     * @param fileName 文件名称
     * @return
     */
    @NLog()
    @RequestMapping(value = "del", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public DggRestResponse delFile(String fileId, String fileName) {
        Annex annex = DggMongoUtils.getMongoTemplate().findOne(new Query(Criteria.where("fileid").is(fileId).and("filename").is(fileName)), Annex.class);
        if(StringUtils.isEmptyObj(annex)){
            // 保存操作日志
            SystemRecord systemRecord = new SystemRecord();
            systemRecord.setSource("5");
            systemRecord.setOperateType("50");
            systemRecord.setWorkId(1L);
            systemRecord.setWorkTableName("annex");
            systemRecord.setRemarks("删除文件：" + fileId + ":" + fileName);
            return super.getSuccessResponse("删除成功！");
        }
        Boolean result = annexService.delFile(fileId, fileName);
        try {
            if (result) {
                // 保存操作日志
                SystemRecord systemRecord = new SystemRecord();
                systemRecord.setSource("5");
                systemRecord.setOperateType("50");
                systemRecord.setWorkId(1L);
                systemRecord.setWorkTableName("annex");
                systemRecord.setRemarks("删除文件：" + fileId + ":" + fileName);
                systemRecordService.save(systemRecord);
                return super.getSuccessResponse("删除成功！");
            } else {
                logger.error("文件删除失败！");
                return super.getFailResponse("删除文件错误，请联系管理员");
            }
        } catch (Exception e) {
            logger.error("文件删除失败！" + e.getLocalizedMessage());
            return super.getFailResponse("删除文件错误，请联系管理员");
        }
    }

    /**
     * 查看附件
     *
     * @param id
     * @return
     */
    @NLog()
    @RequestMapping(value = "view_file")
    @ResponseBody
    public DggRestResponse viewFile(String id, String fileName) {
        annexService.updateFile(id, "view", fileName);
        // 保存操作日志
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setSource("5");
        systemRecord.setOperateType("51");
        systemRecord.setWorkId(1L);
        systemRecord.setWorkTableName("annex");
        systemRecord.setRemarks("点击查看文件：" + id + ":" + fileName);
        systemRecordService.save(systemRecord);
        return this.getSuccessResponse("查看次数增加成功");
    }

    /**
     * 文件下载find_orgs
     *
     * @param id      文件id
     * @param fileUrl 文件地址
     * @return
     */
    @NLog()
    @RequestMapping(value = "download", method = {RequestMethod.GET, RequestMethod.POST})
    public void downloadFile(String id, String fileUrl, String fileName, HttpServletRequest request, HttpServletResponse response) {
        InputStream bis = null;
        OutputStream bos = null;
        URL url = null;
        URLConnection con = null;
        try {
            url = new URL(fileUrl);
            SslUtils.ignoreSsl();
            con = url.openConnection();
            bis = con.getInputStream();
            response.setContentType("text/html;charset=utf-8");
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-msdownload;");
            response.setHeader("content-disposition", "attachment;filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1")+"\"");
            bos = response.getOutputStream();
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            annexService.updateFile(id, "down", fileName);
            // 保存操作日志
            SystemRecord systemRecord = new SystemRecord();
            systemRecord.setSource("5");
            systemRecord.setWorkId(1L);
            systemRecord.setOperateType("51");
            systemRecord.setWorkTableName("annex");
            systemRecord.setRemarks("下载文件：" + id + ":" + fileName);
            systemRecordService.save(systemRecord);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 查看附件
     *
     * @return
     */
    @NLog()
    @RequestMapping(value = "save_old_file")
    @ResponseBody
    public DggRestResponse saveOldFile(String id, String fileName) {
        String fileId = SystemCommonConstant.ANNEX_FILE_ID_PREFIX + "_" + id + "_credential";
        annexService.saveOldFiles(fileId,fileName);
        return this.getSuccessResponse("查看次数增加成功");
    }
}
